import { createRouter, createWebHistory } from 'vue-router'
import LoginView from '../views/LoginViews.vue'
import DashboardView from '../views/DashboardView.vue'
import AdminLayout from '../components/Layout/AdminLayout.vue'

const routes = [
    {
        path: '/',
        redirect: '/login'
    },
    {
        path: '/login',
        name: 'Login',
        component: () => import('../views/LoginViews.vue')
    },
    {
        path: '/admin',
        component: AdminLayout,
        redirect: '/admin/dashboard',
        children: [
            {
                path: 'dashboard',
                name: 'Dashboard',
                component: () => import('../views/DashboardView.vue')
            },
            {
                path: 'artist',
                name: 'ArtistManagement',
                component: () => import('../views/ArtistManagement.vue')
            },
            {
                path: 'playlist',
                name: 'PlaylistManagement',
                component: () => import('../views/PlaylistManagement.vue')
            },
            {
                path: 'album',
                name: 'AlbumManagement',
                component: () => import('../views/AlbumManagement.vue')
            },
            {
                path: 'user',
                name: 'UserManagement',
                component: () => import('../views/UserManagement.vue'),
                meta: { title: '用户管理' }
            },
            {
                path: 'song',
                name: 'SongManagement',
                component: () => import('../views/SongManagement.vue'),
                meta: { title: '歌曲管理' }
            },

        ]
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes
})

router.beforeEach((to, from, next) => {
    const isAuthenticated = localStorage.getItem('auth_token')

    if (to.path === '/login') {
        // 如果已经登录，跳转到 dashboard
        if (isAuthenticated) {
            next('/admin/dashboard')
        } else {
            next() // 允许访问登录页
        }
    } else if (!isAuthenticated) {
        next('/login') // 未登录则跳转到登录页
    } else {
        next() // 已登录，允许访问
    }
})

export default router